const { DataTypes } = require('sequelize');

/**
 * 用户会话记录模型，记录每次登录的会话详情
 * @param {import('sequelize').Sequelize} sequelize Sequelize实例
 */
module.exports = (sequelize) => {
  const UserSession = sequelize.define('UserSession', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'users',
        key: 'id'
      }
    },
    sessionToken: {
      type: DataTypes.STRING(100),
      allowNull: false
    },
    startTime: {
      type: DataTypes.DATE,
      allowNull: false
    },
    endTime: {
      type: DataTypes.DATE,
      allowNull: true
    },
    duration: {
      type: DataTypes.INTEGER,
      allowNull: true,
      comment: '会话持续时间，单位为秒'
    },
    activeTime: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '会话期间活跃时间，单位为秒'
    },
    idleTime: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '会话期间空闲时间，单位为秒'
    },
    ipAddress: {
      type: DataTypes.STRING(45),
      allowNull: true
    },
    userAgent: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    messagesSent: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '本次会话发送消息数量'
    },
    messagesReceived: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '本次会话接收消息数量'
    },
    contactsInteracted: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '本次会话互动的联系人数量'
    },
    status: {
      type: DataTypes.ENUM('active', 'idle', 'closed'),
      defaultValue: 'active'
    },
    whatsappSessionId: {
      type: DataTypes.STRING(100),
      allowNull: true,
      comment: '关联的WhatsApp会话ID'
    },
    lastActivityTime: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '最后活跃时间'
    },
    closeReason: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: '会话关闭原因'
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false
    }
  }, {
    tableName: 'user_sessions',
    timestamps: true,
    indexes: [
      {
        fields: ['userId']
      },
      {
        fields: ['sessionToken']
      },
      {
        fields: ['startTime']
      },
      {
        fields: ['status']
      }
    ]
  });

  // 添加关联
  UserSession.associate = (models) => {
    UserSession.belongsTo(models.User, {
      foreignKey: 'userId',
      as: 'user'
    });
  };

  return UserSession;
}; 